using System;
using System.Collections.Generic;
using System.Xml;

namespace pginstaller.tasks
{
    public class WixProcessor
    {
        public delegate string NodeProcessor(string instr);
        public static void ProcessWixNode(XmlNode node, NodeProcessor processor)
        {
            foreach (XmlNode attr in node.Attributes)
            {
                if (attr.Value == null || attr.Name == null || attr.Value == "")
                    continue;
                if (attr.Name == "Text" && node.Name == "Control" &&
                    (
                     node.Attributes.GetNamedItem("Type").Value == "Icon" ||
                     node.Attributes.GetNamedItem("Type").Value == "Bitmap" ||
                     (node.Attributes.GetNamedItem("Type").Value == "PushButton" && node.Attributes.GetNamedItem("Icon") != null && node.Attributes.GetNamedItem("Icon").Value == "yes")
                    )
                   )
                {
                    // Ignore
                    continue;
                }
                else if (attr.Name == "Description" || attr.Name == "Title" || attr.Name == "Text" || attr.Name == "ToolTip")
                {
                    attr.Value = processor(attr.Value);
                }
                else if (node.Name == "Shortcut" && attr.Name == "Name")
                {
                    attr.Value = processor(attr.Value);
                }
                else if (node.Name == "Directory" && attr.Name == "Name" && node.Attributes.GetNamedItem("Id").Value.Substring(0, 2) == "PM" && node.Attributes.GetNamedItem("Id").Value != "PMDir")
                {
                    attr.Value = processor(attr.Value);
                }
            }

            foreach (XmlNode subnode in node.ChildNodes)
            {
                if (subnode.NodeType == XmlNodeType.Element)
                    ProcessWixNode(subnode, processor);
                else if (subnode.NodeType == XmlNodeType.Text)
                {
                    if (node.Name == "ProgressText" || node.Name == "Text" || node.Name == "UIText")
                    {
                        node.InnerText = processor(node.InnerText);
                    }
                }
            }
        }
    }
}